<?php

namespace Iwesen\Sem\Track\Advertisers;

class Kuaishou
{
    //列举常用的转化类型
    const API_SUBMIT = 9; //表单提交';
    const API_EFFECT_CARD = 44; //有效获客';
    const API_PAY = 69; //购买课程（限教育）

    protected $api = 'http://ad.partner.gifshow.com/track/activate';

    public function callback($param)
    {
        if (!isset($param['eventType']) || !$param['eventType']) {
            $param['eventType'] = config('sem-track.kuaishou.eventType');
            if (!$param['eventType']) {
                throw new \Exception('eventType参数不能为空');
            }
        }
        if (!isset($param['callback'])) {
            throw new \Exception('callback参数不能为空');
        }

        if($param['eventType']==self::API_PAY &&(!isset($param['purchaseAmount']) || !$param['purchaseAmount'])){
            throw new \Exception('当转化类型为[教育正价课付费]时，purchaseAmount参数不能为空');
        }

        try {
            $time = time()*1000;

            $url = $this->api."?callback={$param['callback']}&event_type={$param['eventType']}&event_time={$time}";
            if($param['eventType']==self::API_PAY){
                $url.='&purchase_amount='.$param['purchaseAmount'];
            }

            $result = (new Request())->_request($url);
            $data = json_decode($result,true);
            if($data['result']==1){
                return 'success';
            }
            return 'fail';
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage(), $e->getCode(), $e);
        }
    }
}
